package com.yjd.back.app;

import com.yjd.comm.app.model.AppVersionModel;
import com.yjd.comm.app.service.IAppVersionService;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.PagerHtmlModel;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.fs.util.FileUtil;
import com.yjd.comm.resource.model.ResourceModel;
import com.yjd.comm.util.*;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 后台app版本控制
 * Created by yangchangyan on 2017/7/18.
 */
@Controller("com.yjd.back.app.AppVersionControl")
@Scope("prototype")
@RequestMapping("/app")
public class AppVersionControl extends BaseControl {

    @Resource
    private IAppVersionService appVersionService;

    @RequestMapping(value = "/all")
    public String allVersion() throws Exception {

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("sort", " last_update_time desc ");
        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(
                this.appVersionService.getPageModel(paramMap, DbWREnums.READ), paramMap,
                ServletUtil.getUrl("/app/all"));

        AppVersionModel avm = null;
        for (Object obj : pager.getPagerModel().getDataList()) {
            avm = (AppVersionModel) obj;
            avm.getStrMap().put("create_time", DateUtil.timestampToDateString(avm.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            avm.getStrMap().put("last_update_time", DateUtil.timestampToDateString(avm.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
        }

        request.setAttribute("maps", paramMap);
        request.setAttribute("pager", pager);

        return "user.app.version.all";
    }

    @RequestMapping(value = "/version/active")
    public void activeVersion(Long id, String device_type) throws Exception {
        if (StringUtil.isEmpty(device_type) || null == id) {
            this.errorMsg("参数异常");
            return;
        }
        device_type = device_type.toLowerCase();

        // 任何一个时刻只允许激活一个版本
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        List<AppVersionModel> versions = appVersionService.getModelList(FrameUtil.newHashMap("device_type", device_type), DbWREnums.READ);
        for(AppVersionModel avm : versions){
            if(avm.getStatus() == 0){
                this.errorMsg("请先禁用其他["+device_type+"]版本");
                return;
            }
        }
        AppVersionModel avm = new AppVersionModel();
        avm.setId(id);
        avm.setStatus(0); // 0表示正常,1表示当前数据包在锁定状态无法下载使用,2数据包正在更新无法下载使用
        avm.setDevice_type(device_type);
        appVersionService.update(avm);
        this.successMsg( ServletUtil.getUrl("/app/all"), "处理成功");
    }

    @RequestMapping(value = "/version/inactive")
    public void inactiveVersion(Long id) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        AppVersionModel avm = new AppVersionModel();
        avm.setId(id);
        avm.setStatus(1); // 0表示正常,1表示当前数据包在锁定状态无法下载使用,2数据包正在更新无法下载使用
        appVersionService.update(avm);
        this.successMsg( ServletUtil.getUrl("/app/all"), "处理成功");
    }

    @RequestMapping(value = "/to/upload")
    public String toUpload() throws Exception {
        return "user.app.version.upload";
    }

    @RequestMapping(value = "/upload/android")
    public void appUploadAndroid(@RequestParam("app") MultipartFile appFile, AppVersionModel avm) throws Exception {
        if(!validate(avm)){
            this.errorMsg("参数异常");
            return;
        }

        // IOS没有上传文件，所以只需验证android即可
        if("android".equals(avm.getDevice_type())){
            if(null == appFile || appFile.isEmpty()){
                this.errorMsg(null, "请选择文件");
                return;
            }
            if(!appFile.getOriginalFilename().endsWith(".apk")){
                this.errorMsg(null, "请选择apk文件");
                return;
            }
        }


        // 上传文件
        ResourceModel res = new ResourceModel();
        res.setRef_type(ReferenceTypeEnum.APP.getCode());
        String filePath = FileUtil.uploadFileToRemote(appFile, ReferenceTypeEnum.APP, res);

        // 记录版本信息
        avm.setStatus(1); // 0表示正常,1表示当前数据包在锁定状态无法下载使用,2数据包正在更新无法下载使用
        avm.setUrl(ServletUtil.getFileUrl(filePath));
        updateVersionRecord(avm);

        this.successMsg( "/app/all"  + ServletUtil.getUrlStuff()+"?device_type="+avm.getDevice_type(), "处理成功");
    }

    @RequestMapping(value = "/upload/ios")
    public void appUploadIos(AppVersionModel avm) throws Exception {

        if(!validate(avm) || StringUtil.isEmpty(avm.getUrl())){
            this.errorMsg("参数异常");
            return;
        }

        // 记录版本信息
        avm.setStatus(1); // 0表示正常,1表示当前数据包在锁定状态无法下载使用,2数据包正在更新无法下载使用
        updateVersionRecord(avm);

        this.successMsg( "/app/all"  + ServletUtil.getUrlStuff()+"?device_type="+avm.getDevice_type(), "处理成功");
    }

    private boolean validate(AppVersionModel avm){
        if (StringUtil.isEmpty(avm.getDevice_type()) ||
                StringUtil.isEmpty(avm.getPackage_name()) ||
                StringUtil.isEmpty(avm.getApp_version())) {
            return false;
        }

        // 统一小写保存
        avm.setDevice_type(avm.getDevice_type().toLowerCase());

        if( !"android".equals(avm.getDevice_type()) && !"ios".equals(avm.getDevice_type()) ){
            return false;
        }

        return true;
    }

    private void updateVersionRecord(AppVersionModel avm) throws Exception {
        // 更新记录
        Long currentTime = FrameUtil.getTime();
        avm.setStatus(1); // 0表示正常,1表示当前数据包在锁定状态无法下载使用,2数据包正在更新无法下载使用
        avm.setUrl_type(1);
        avm.setCreate_time(currentTime);
        avm.setLast_update_time(currentTime);
        appVersionService.insert(avm);
    }
}
